//
//  TSPushNotificationView.m
//  TTLoveCar
//
//  Created by 王洋 on 2017/8/14.
//  Copyright © 2017年 王洋. All rights reserved.
//

#import "TSPushNotificationView.h"
#import "UIImage+Crop.h"
#import "UIImage+ImageEffects.h"

#define kAnimationDuration 0.3         //动画弹出时间

static NSTimeInterval duration = 10;  // view默认显示的时间，这个时间到了之后会自动消失

#define PushNotification_Height  90  //高度

#define kBgColor       [UIColor blackColor]

#define kLeftPadding    10      //左右边距

#define kCornerRadius   10       //圆角值

@interface TSPushNotificationItem ()



@end

@implementation TSPushNotificationItem

+ (instancetype) pushItemWith:(NSString *)message body:(NSDictionary *)body target:(id)target action:(SEL)action{
    [Utilities tapticEngineWork];
    return [[TSPushNotificationItem alloc] init:message body:body target:target action:action];
}

- (id) init:(NSString*)message body:(NSDictionary*)body target:(id)target action:(SEL)action
{
    NSParameterAssert(message.length);
    
    self = [super init];
    if (self) {
        
        _message = message;
        _body = body;
        _action = action;
        _target = target;
    }
    return self;
}
- (void) performAction
{
    __strong id target = self.target;
    
    if (target && [target respondsToSelector:_action]) {
        
        [target performSelectorOnMainThread:_action withObject:self waitUntilDone:YES];
    }
}

@end

@interface TSPushNotificationView ()

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) TSPushNotificationItem *item;
@end

@implementation TSPushNotificationView {

}

//- (UIImage *)ct_imageFromImage:(UIImage *)image inRect:(CGRect)rect{
//
//    //把像 素rect 转化为 点rect（如无转化则按原图像素取部分图片）
//    CGFloat scale = [UIScreen mainScreen].scale;
//    CGFloat x= rect.origin.x*scale,y=rect.origin.y*scale,w=rect.size.width*scale,h=rect.size.height*scale;
//    CGRect dianRect = CGRectMake(x, y, w, h);
//
//    //截取部分图片并生成新图片
//    CGImageRef sourceImageRef = [image CGImage];
//    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, dianRect);
//    UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
//    return newImage;
//}


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

static TSPushNotificationView *gPushView;

+ (instancetype)pushNotificationView {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        gPushView = [[TSPushNotificationView alloc] initWithFrame:CGRectZero];
    });
    return gPushView;
}

+ (void)showPushViewInView:(UIView *)inview item:(TSPushNotificationItem *)item {
    
    [[TSPushNotificationView pushNotificationView]showPushViewInView:inview item:item];
    [TSPushNotificationView  performSelector:@selector(dismissPushView) withObject:nil afterDelay:duration];
}

+ (void)dismissPushView {
    [[TSPushNotificationView pushNotificationView] dismissPushView:YES];
}

- (void)showPushViewInView:(UIView *)inview item:(TSPushNotificationItem*)item{
    [self playSound];
    if (!item) {
        return;
    }
    self.frame = CGRectMake(kLeftPadding, StatusBar_Height, TTScreenWidth - kLeftPadding * 2, PushNotification_Height);
    self.item = item;
    [self mkBgView:inview];
    self.contentView = [self mkContentView];
    [inview addSubview:self];
    
    WEAKSELF
    if ([UIView respondsToSelector:@selector(animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:)]) {
        [UIView animateWithDuration:kAnimationDuration+0.2
                              delay:0.0
             usingSpringWithDamping:0.6
              initialSpringVelocity:4.0
                            options:UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionCurveEaseInOut
                         animations:^
         {
             weakSelf.contentView.top = 0;
         }
                         completion:^(BOOL finished)
         {
         }];
        
    }else {
        
        [UIView animateWithDuration:kAnimationDuration animations:^(void){
            weakSelf.contentView.top = 0;
        }completion:^(BOOL completed){
        }];
    }    
}

-(void)playSound {
NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];

if (timeInterval >=  3.0 || !self.lastPlaySoundDate) {
    //如果距离上次响铃和震动时间太短, 则跳过响铃
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
    NSString *msgVoiceSetting = [userD objectForKey:@"msgVoiceSetting"];
    if (!msgVoiceSetting.integerValue){
        //收到消息时，播放音频
//        [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    }
    NSString *msgShockSetting = [userD objectForKey:@"msgShockSetting"];
    if (!msgShockSetting.integerValue){
        //收到消息时，震动
//        [[EMCDDeviceManager sharedInstance] playVibration];
    }
}
}

- (UIView*)mkContentView {
    if (self.contentView) {
        for (UIView *view in self.contentView.subviews) {
            [view removeFromSuperview];
        }
    }
    
    if (!self.contentView) {
        self.contentView = [[UIView alloc]initWithFrame:CGRectMake(0, - PushNotification_Height, TTScreenWidth - 2 * kLeftPadding, PushNotification_Height)];
        self.contentView.backgroundColor = UIColorHex(0xfafafa);
        self.contentView.userInteractionEnabled = YES;
        self.contentView.layer.cornerRadius = kCornerRadius;
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]initWithTarget:self
                                                                                 action:@selector(performAction:)];
        
        UISwipeGestureRecognizer * recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeAction:)];
        [recognizer setDirection:(UISwipeGestureRecognizerDirectionUp)];
        
        [self.contentView addGestureRecognizer:recognizer];
        [self.contentView addGestureRecognizer:gesture];

        [self addSubview:self.contentView];
    }

    UIImageView *backgroundImageView = [[UIImageView alloc]init];
    backgroundImageView.layer.cornerRadius = 6.0f;
    backgroundImageView.clipsToBounds = YES;
    [backgroundImageView setImage:[UIImage imageNamed:@"huayuangou_icon"]];
    [self.contentView addSubview:backgroundImageView];


    [backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.contentView);
        make.width.height.mas_equalTo(60);
        make.right.mas_equalTo(-10);
//        make.left.right.top.bottom.mas_equalTo(self.contentView);
    }];
    
    UILabel *appNameLab = [[UILabel alloc] init];
    appNameLab.backgroundColor = [UIColor clearColor];
    appNameLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
    appNameLab.textAlignment = NSTextAlignmentLeft;
    appNameLab.textColor = UIColorHex(0x333333);
    appNameLab.text = @"花园购";
    
    UILabel *ganggangLab = [[UILabel alloc] init];
    ganggangLab.backgroundColor = [UIColor clearColor];
    ganggangLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
    ganggangLab.textAlignment = NSTextAlignmentLeft;
    ganggangLab.textColor = UIColorHex(0x999999);
    ganggangLab.text = @"刚刚";

    UILabel *messageLabel = [[UILabel alloc]init];
    messageLabel.backgroundColor = [UIColor clearColor];
    messageLabel.font = [UIFont systemFontOfSize:14];
    messageLabel.textColor = UIColorHex(0x666666);
    messageLabel.numberOfLines = 2;
    messageLabel.textAlignment = NSTextAlignmentLeft;
    messageLabel.text = self.item.message;

    UIView *indicatorView = [[UIView alloc]init];
    indicatorView.layer.cornerRadius = 3;
    indicatorView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
    [self.contentView addSubview:messageLabel];
    [self.contentView addSubview:appNameLab];
    [self.contentView addSubview:ganggangLab];

    [self.contentView addSubview:indicatorView];

    [indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.contentView.mas_centerX);;
        make.height.mas_equalTo(6);
        make.width.mas_equalTo(60);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-5);
    }];
    
    [messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(20);
        make.bottom.mas_equalTo(indicatorView.mas_top).offset(-8);
        make.right.mas_equalTo(backgroundImageView.mas_left).offset(-10);
        make.height.mas_equalTo(36);
    }];
    
    [appNameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(20);
        make.bottom.mas_equalTo(messageLabel.mas_top).offset(-6);
    }];
    
    [ganggangLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(appNameLab.mas_right).offset(20);
        make.centerY.mas_equalTo(appNameLab);
    }];
    
    return self.contentView;
}

- (void)mkBgView:(UIView*)inView {
    self.backgroundColor = [UIColor clearColor];
}

- (void)hiddenSelf {
    [[TSPushNotificationView pushNotificationView] dismissPushView:YES];
}

- (void)dismissPushView:(BOOL)flag {
    if (!flag) {
        return;
    }
    WEAKSELF
    [UIView animateWithDuration:kAnimationDuration animations:^(void){
        weakSelf.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.0];
        weakSelf.contentView.top = -PushNotification_Height;
    }completion:^(BOOL finished){
        [weakSelf removeFromSuperview];
    }];
    
}

//滑动隐藏
- (void)handleSwipeAction:(id)sender {

    [self dismissPushView:YES];
    [self.item performAction];
}

//点击跳转
- (void)performAction:(id)sender {

    if ([self.item.body.allKeys containsObject:@"payload"]) {

        NSString *payload = [self.item.body valueForKey:@"payload"];
        [[TT_JumpManager sharedManager] jumpWithPayload:payload];
        
    } else if ([self.item.body.allKeys containsObject:@"type"]) {
        
        [[TT_JumpManager sharedManager] jumpWithWebParamDic:self.item.body];
    }
    [self dismissPushView:YES];

}

- (void)dealloc {
    NSLog(@"share view dealloc");
}

@end
